<template>
  <div class="page page-login" v-loading:bar.fullscreen="loading">
    <h3 class="login-title">验证码登录</h3>
    <lt-form label-position="top">
      <lt-form-item>
        <div class="form-row-content">
          <div class="icon-wrapper">
            <Icon class="login-icon" icon="mi:mobile" />
          </div>
          <lt-md-input
            class="login-input"
            v-model="formData.phone"
            label="手机号"
            html-type="tel"
          ></lt-md-input>
        </div>
      </lt-form-item>
      <lt-form-item>
        <div class="form-row-content">
          <div class="icon-wrapper">
            <Icon icon="tabler:device-mobile-code" class="login-icon" />
          </div>
          <lt-md-input
            class="login-input"
            v-model="formData.code"
            label="验证码"
            html-type="tel"
          ></lt-md-input>
          <lt-button
            type="primary"
            text
            class="btn-code"
            @click="handleQueryCode"
            :disabled="codeBtnDisable && timeDown < 0"
            >{{ timeDown >= 0 ? timeDown + "s" : "获取验证码" }}</lt-button
          >
        </div>
      </lt-form-item>
      <lt-form-item>
        <div class="form-row-content button-row">
          <lt-button
            type="primary"
            round
            class="btn-submit"
            :disabled="submitBtnDisable"
            @click="handleSubmit"
          >
            <Icon icon="bi:arrow-right" />
          </lt-button>
        </div>
      </lt-form-item>
    </lt-form>
  </div>
</template>

<script setup lang="ts">
import Validator from "ph-utils/validator";
import { Icon } from "@iconify/vue";
// import { set } from "ph-utils/storage";
import { useRouter } from "vue-router";
import { reactive, ref, watch, nextTick, onUnmounted } from "vue";

const router = useRouter();

let validator = new Validator([
  { key: "phone", rules: ["mobile"] },
  { key: "code", rules: [/^\d{6}$/], message: "请输入正确的验证码" },
]);

const formData = reactive({
  phone: "",
  code: "",
});

let loading = ref(false);
let timeDown = ref(-1);
let _t = -1;

const codeBtnDisable = ref(true);
const submitBtnDisable = ref(true);

async function validData(key: string, value: string) {
  const limitLen = key === "phone" ? 11 : 6;
  let errKey = "";
  if (value.length === limitLen) {
    // 验证数据
    try {
      validator.validateKey(key, value);
      await validator.validate(formData);
      codeBtnDisable.value = false;
      submitBtnDisable.value = false;
    } catch (error: any) {
      errKey = error.key;
    }
  } else {
    errKey = key;
  }
  if (errKey === "phone") {
    codeBtnDisable.value = true;
  } else if (errKey === "code") {
    codeBtnDisable.value = false;
    submitBtnDisable.value = true;
  }
}

watch(
  () => formData.phone,
  (v) => {
    nextTick(() => {
      if (v.length > 11) {
        formData.phone = v.substring(0, 11);
      }
      validData("phone", formData.phone).then();
    });
  }
);

watch(
  () => formData.code,
  (v) => {
    nextTick(() => {
      if (v.length > 6) {
        formData.code = v.substring(0, 6);
      }
      validData("code", formData.code).then();
    });
  }
);

function handleQueryCode() {
  if (!loading.value && timeDown.value < 0) {
    validator.validateKey("phone", formData.phone).then(
      () => {
        // 调用获取验证码接口

        // 倒计时
        timeDown.value = 60;
        _t = setInterval(() => {
          timeDown.value--;
          if (timeDown.value < 0) {
            clearInterval(_t);
          }
        }, 1000) as any as number;
      },
      (err) => {
        NtMessage.error(err.message);
      }
    );
  }
}

async function handleSubmit() {
  if (!loading.value) {
    try {
      await validator.validate(formData);
      loading.value = true;
      // const res = await login(formData.phone, formData.code);
      // set("user_token", res.token, { storage: "local" });
      router.push("/");
    } catch (error: any) {
      if (error.status == null) {
        NtMessage.error(error.message);
      }
    } finally {
      loading.value = false;
    }
  }
}

onUnmounted(() => {
  clearInterval(_t);
  validator = null as any;
});
</script>

<style lang="less">
.page-login {
  padding: 30px 15px 15px 15px;
  background: linear-gradient(#e9efff, #f5f5f5);
  height: 100%;
  box-sizing: border-box;
  .login-title {
    font-weight: 500;
    font-size: 18px;
    text-align: center;
    margin-bottom: 1.8em;
  }
  .nt-form-item {
    margin-bottom: 50px;
  }
  .form-row-content {
    display: flex;
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #dedede;
  }
  .button-row {
    border-bottom-width: 0;
    justify-content: center;
    padding-top: 15px;
  }

  .icon-wrapper {
    width: 20px;
  }
  .login-icon {
    font-size: 20px;
    color: #666666;
    vertical-align: middle;
  }
  .login-input {
    flex-grow: 1;
    margin-left: 10px;
  }
  .btn-code {
    flex-shrink: 0;
    margin-left: 10px;
  }

  .btn-submit {
    --nt-btn-disabled-background: #d9d9d9;
    --nt-btn-disabled-color: #ffffff;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    font-size: 24px;
  }
}
</style>
